"use client";

import {
  ChevronDown,
  ChevronRight,
  Edit,
  Home,
  LogOut,
  Plus,
  Save,
  Settings,
  Trash2,
  User,
  X,
} from "lucide-react";
import * as React from "react";
import ReactMarkdown from "react-markdown";
import rehypeHighlight from 'rehype-highlight';
import remarkGfm from 'remark-gfm';

import { Button } from "@/components/ui/button";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn } from "@/lib/utils";

import EditorAssistant from "../components/EditorAssistant";
import EnterpriseLibrary from "../components/EnterpriseLibrary";
import MaterialLibrary from "../components/MaterialLibrary";
import StandardLibrary from "../components/StandardLibrary";
import TemplateSelectionModal from "../components/TemplateSelectionModal";
import TopFunctionBar from "../components/TopFunctionBar";

import { mdxComponents } from './profile/mdx-config'

const initialArticleStructure = [
  {
    id: "1",
    title: "Chapter 1: Introduction",
    type: "chapter",
    content:
      "# Chapter 1: Introduction\n\nThis is the introduction chapter of our document.",
    children: [
      {
        id: "1.1",
        title: "1.1 Background",
        type: "section",
        content:
          "## 1.1 Background\n\nThis is the background section of Chapter 1.",
        children: [],
      },
      {
        id: "1.2",
        title: "1.2 Objectives",
        type: "section",
        content: "## 1.2 Objectives\n\nHere are the objectives of our study.",
        children: [],
      },
    ],
  },
  {
    id: "2",
    title: "Chapter 2: Methodology",
    type: "chapter",
    content:
      "# Chapter 2: Methodology\n\nThis chapter describes our methodology.",
    children: [
      {
        id: "2.1",
        title: "2.1 Research Design",
        type: "section",
        content: "## 2.1 Research Design\n\nOur research design involves...",
        children: [],
      },
      {
        id: "2.2",
        title: "2.2 Data Collection",
        type: "section",
        content: "## 2.2 Data Collection\n\nWe collected data through...",
        children: [],
      },
    ],
  },
];

interface TreeItemData {
  id: string;
  title: string;
  type: string;
  content: string;
  children: TreeItemData[];  // 明确定义为递归类型
}

const TreeItem = ({
  item,
  onSelect,
  onAddChild,
  onDelete,
  onUpdate,
  selectedId,
  isEditMode,
  depth = 0,
}: {
  item: TreeItemData;
  onSelect: (item: TreeItemData) => void;
  onAddChild: (item: TreeItemData) => void;
  onDelete: (item: TreeItemData) => void;
  onUpdate: (id: string, title: string) => void;
  selectedId: string | null;
  isEditMode: boolean;
  depth?: number;
}) => {
  const [isOpen, setIsOpen] = React.useState(false);
  const [isEditing, setIsEditing] = React.useState(false);
  const [editedTitle, setEditedTitle] = React.useState(item.title);
  const hasChildren = item.children && item.children.length > 0;

  const handleEdit = () => {
    setIsEditing(true);
  };

  const handleSave = () => {
    onUpdate(item.id, editedTitle);
    setIsEditing(false);
  };

  const handleCancel = () => {
    setEditedTitle(item.title);
    setIsEditing(false);
  };

  const getIndentClass = () => {
    if (item.type === "chapter") return "pl-0";
    if (item.type === "section") return "pl-2";
    return `pl-${2 * (depth + 1)}`;
  };

  return (
    <Collapsible open={isOpen} onOpenChange={setIsOpen}>
      <div
        className={`flex items-center justify-between ${
          depth > 0 ? `ml-${depth * 2}` : ""
        }`}
      >
        <div className="flex items-center flex-grow overflow-hidden">
          <CollapsibleTrigger asChild>
            <button
              className={cn(
                "flex items-center py-1 text-sm transition-colors hover:bg-accent hover:text-accent-foreground",
                item.type === "chapter" && "font-semibold",
                getIndentClass()
              )}
            >
              {hasChildren ? (
                isOpen ? (
                  <ChevronDown className="mr-1 h-4 w-4 flex-shrink-0" />
                ) : (
                  <ChevronRight className="mr-1 h-4 w-4 flex-shrink-0" />
                )
              ) : (
                <span className="w-5 flex-shrink-0" />
              )}
              {isEditing ? (
                <Input
                  value={editedTitle}
                  onChange={(e) => setEditedTitle(e.target.value)}
                  className="h-6 py-0 px-1 text-sm"
                  onKeyDown={(e) => e.key === "Enter" && handleSave()}
                />
              ) : (
                <span
                  className={cn(
                    "flex-1 text-left truncate",
                    selectedId === item.id && "text-primary font-medium"
                  )}
                  onClick={() => onSelect(item)}
                >
                  {item.title}
                </span>
              )}
            </button>
          </CollapsibleTrigger>
        </div>
        {isEditMode && (
          <div className="flex items-center">
            {isEditing ? (
              <>
                <Button variant="ghost" size="icon" onClick={handleSave}>
                  <Save className="h-4 w-4" />
                </Button>
                <Button variant="ghost" size="icon" onClick={handleCancel}>
                  <X className="h-4 w-4" />
                </Button>
              </>
            ) : (
              <>
                <Button variant="ghost" size="icon" onClick={handleEdit}>
                  <Edit className="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => onAddChild(item)}
                >
                  <Plus className="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => onDelete(item)}
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </>
            )}
          </div>
        )}
      </div>
      {hasChildren && (
        <CollapsibleContent>
          {item.children.map((child) => (
            <TreeItem
              key={child.id}
              item={child}
              onSelect={onSelect}
              onAddChild={onAddChild}
              onDelete={onDelete}
              onUpdate={onUpdate}
              selectedId={selectedId}
              isEditMode={isEditMode}
              depth={depth + 1}
            />
          ))}
        </CollapsibleContent>
      )}
    </Collapsible>
  );
};

interface MarkdownEditorProps {
  content: string;
  onChange: (content: string) => void;
  currentLine: number;
  onLineClick: (index: number) => void;
  onAITrigger: (e: React.SyntheticEvent) => void;
}

const MarkdownEditor = ({
  content,
  onChange,
  currentLine,
  onLineClick,
  onAITrigger,
}: MarkdownEditorProps) => {
  const [lines, setLines] = React.useState(content.split("\n"));
  const [editingLine, setEditingLine] = React.useState(currentLine);
  const textareaRef = React.useRef<HTMLTextAreaElement>(null);

  React.useEffect(() => {
    setLines(content.split("\n"));
  }, [content]);

  const currentLineContent = lines[editingLine];

  React.useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = "auto";
      textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
    }
  }, [currentLineContent]);

  const handleLineClick = (index: number) => {
    setEditingLine(index);
    onLineClick(index);
  };

  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const newLines = [...lines];
    newLines[editingLine] = e.target.value;
    setLines(newLines);
    onChange(newLines.join("\n"));
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter") {
      e.preventDefault();
      const newLines = [...lines];
      const cursorPosition = (e.target as HTMLTextAreaElement).selectionStart;
      const currentLine = newLines[editingLine];
      const textBeforeCursor = currentLine.slice(0, cursorPosition);
      const textAfterCursor = currentLine.slice(cursorPosition);

      newLines[editingLine] = textBeforeCursor;
      newLines.splice(editingLine + 1, 0, textAfterCursor);
      setLines(newLines);
      onChange(newLines.join("\n"));
      setEditingLine(editingLine + 1);
      setTimeout(() => {
        if (textareaRef.current) {
          textareaRef.current.focus();
          textareaRef.current.selectionStart =
            textareaRef.current.selectionEnd = 0;
        }
      }, 0);
    } else if (e.key === " " && lines[editingLine] === "") {
      e.preventDefault();
      onAITrigger(e);
    } else if (
      e.key === "Backspace" &&
      (e.target as HTMLTextAreaElement).selectionStart === 0 &&
      (e.target as HTMLTextAreaElement).selectionEnd === 0 &&
      editingLine > 0
    ) {
      e.preventDefault();
      const newLines = [...lines];
      const currentLineContent = newLines[editingLine];
      const previousLineContent = newLines[editingLine - 1];
      newLines[editingLine - 1] = previousLineContent + currentLineContent;
      newLines.splice(editingLine, 1);
      setLines(newLines);
      onChange(newLines.join("\n"));
      setEditingLine(editingLine - 1);
      setTimeout(() => {
        if (textareaRef.current) {
          const newCursorPosition = previousLineContent.length;
          textareaRef.current.setSelectionRange(
            newCursorPosition,
            newCursorPosition
          );
        }
      }, 0);
    } else if (
      e.key === "Delete" &&
      (e.target as HTMLTextAreaElement).selectionStart === (e.target as HTMLTextAreaElement).value.length &&
      (e.target as HTMLTextAreaElement).selectionEnd === (e.target as HTMLTextAreaElement).value.length &&
      editingLine < lines.length - 1
    ) {
      e.preventDefault();
      const newLines = [...lines];
      const currentLineContent = newLines[editingLine];
      const nextLineContent = newLines[editingLine + 1];
      newLines[editingLine] = currentLineContent + nextLineContent;
      newLines.splice(editingLine + 1, 1);
      setLines(newLines);
      onChange(newLines.join("\n"));
      setTimeout(() => {
        if (textareaRef.current) {
          const newCursorPosition = currentLineContent.length;
          textareaRef.current.setSelectionRange(
            newCursorPosition,
            newCursorPosition
          );
        }
      }, 0);
    }
  };

  const getHeadingClass = (line: string) => {
    if (line.startsWith("# ")) return "text-4xl font-bold";
    if (line.startsWith("## ")) return "text-3xl font-bold";
    if (line.startsWith("### ")) return "text-2xl font-bold";
    if (line.startsWith("#### ")) return "text-xl font-bold";
    if (line.startsWith("##### ")) return "text-lg font-bold";
    if (line.startsWith("###### ")) return "text-base font-bold";
    if (line.startsWith("####### ")) return "text-base";
    return "";
  };

  return (
    <div className="relative border-l border-r border-gray-200">
      {lines.map((line, index) => (
        <div
          key={index}
          className={`flex items-center min-h-[2.5em] ${
            index === editingLine
              ? "bg-blue-50 border-l-4 border-blue-500"
              : "border-l-4 border-transparent"
          }`}
          onClick={() => handleLineClick(index)}
        >
          {index === editingLine ? (
            <textarea
              ref={textareaRef}
              value={line}
              onChange={handleChange}
              onKeyDown={handleKeyDown}
              className="w-full px-3 py-2 resize-none overflow-hidden focus:outline-none focus:ring-0 bg-transparent"
              placeholder={
                line === "" ? "在空行处按下空格键，呼唤出编辑器助理" : ""
              }
              rows={1}
              style={{
                maxWidth: "100ch",
                whiteSpace: "pre-wrap",
                wordWrap: "break-word",
              }}
            />
          ) : (
            <div
              className={`px-4 py-2 w-full ${getHeadingClass(line)}`}
              style={{
                maxWidth: "100ch",
                whiteSpace: "pre-wrap",
                wordWrap: "break-word",
              }}
            >
              <ReactMarkdown>{line || " "}</ReactMarkdown>
            </div>
          )}
        </div>
      ))}
    </div>
  );
};

const ChatPanel = () => {
  const [messages, setMessages] = React.useState(() => [{
    role: "assistant",
    content: "您好！我是您的对话助理。有什么我可以帮您的吗？",
  }]);
  const [input, setInput] = React.useState("");

  const handleSend = () => {
    if (input.trim()) {
      setMessages([...messages, { role: "user", content: input }]);
      setInput("");
      setTimeout(() => {
        setMessages((prev) => [
          ...prev,
          { role: "assistant", content: `您说: "${input}"` },
        ]);
      }, 1000);
    }
  };

  return (
    <div className="flex flex-col h-full">
      <div className="flex-1 overflow-auto p-4 space-y-4">
        {messages.map((message, index) => (
          <div
            key={index}
            className={`flex ${
              message.role === "user" ? "justify-end" : "justify-start"
            }`}
          >
            <div
              className={`max-w-[70%] p-2 rounded ${
                message.role === "user"
                  ? "bg-primary text-primary-foreground"
                  : "bg-muted"
              }`}
            >
              {message.content}
            </div>
          </div>
        ))}
      </div>
      <div className="p-4 border-t flex">
        <Input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="入..."
          className="flex-1 mr-2"
          onKeyDown={(e) => e.key === "Enter" && handleSend()}
        />
        <Button onClick={handleSend}>发送</Button>
      </div>
    </div>
  );
};

interface FullTextScrollBarProps {
  structure: TreeItemData[];
  selectedItemId: string | null;
  onItemSelect: (id: string) => void;
}

const FullTextScrollBar = ({ structure, selectedItemId, onItemSelect }: FullTextScrollBarProps) => {
  const flattenStructure = (items: TreeItemData[], depth = 0): Array<{ id: string; title: string; depth: number }> => {
    return items.flatMap((item) => [
      { id: item.id, title: item.title, depth },
      ...flattenStructure(item.children || [], depth + 1),
    ]);
  };

  const flatItems = flattenStructure(structure);
  const selectedIndex = flatItems.findIndex(
    (item) => item.id === selectedItemId
  );
  const scrollPosition = (selectedIndex / (flatItems.length - 1)) * 100;

  const handleWheel = (e: React.WheelEvent<HTMLDivElement>) => {
    e.preventDefault();
    const direction = e.deltaY > 0 ? 1 : -1;
    const newIndex = Math.max(
      0,
      Math.min(flatItems.length - 1, selectedIndex + direction)
    );
    onItemSelect(flatItems[newIndex].id);
  };

  return (
    <div
      className="w-1 bg-gray-100 relative cursor-pointer"
      onWheel={handleWheel}
    >
      <div
        className="w-full bg-gray-300 rounded-full"
        style={{
          height: `${Math.max(5, 100 / flatItems.length)}%`,
          top: `${Math.min(scrollPosition, 100 - 100 / flatItems.length)}%`,
          position: "absolute",
          transition: "top 0.3s ease-out",
        }}
      />
    </div>
  );
};

const mdxOptions = {
  remarkPlugins: [remarkGfm],
  rehypePlugins: [rehypeHighlight]
};

export default function BlockPage() {
  const [articleStructure, setArticleStructure] = React.useState<TreeItemData[]>(initialArticleStructure);
  const [selectedItem, setSelectedItem] = React.useState<TreeItemData | null>(null);
  const [searchTerm, setSearchTerm] = React.useState("");
  const [standardLibraryPanelState, setStandardLibraryPanelState] =
    React.useState<"open" | "closed">("closed");
  const [materialLibraryPanelState, setMaterialLibraryPanelState] =
    React.useState<"open" | "closed">("closed");
  const [enterpriseLibraryPanelState, setEnterpriseLibraryPanelState] =
    React.useState<"open" | "closed">("closed");
  const [isEditMode, setIsEditMode] = React.useState(false);
  const [currentVersion, setCurrentVersion] = React.useState("1.0");
  const [versions, setVersions] = React.useState([
    "1.0",
    "1.1",
    "1.2",
    "2.0",
    "2.1",
  ]);
  const [isVersionDialogOpen, setIsVersionDialogOpen] = React.useState(false);
  const [editingVersion, setEditingVersion] = React.useState<string | null>(null);
  const [newVersionName, setNewVersionName] = React.useState("");
  const [isPreviewMode, setIsPreviewMode] = React.useState(false);
  const [currentLine, setCurrentLine] = React.useState(0);
  const [isTemplateModalOpen, setIsTemplateModalOpen] = React.useState(false);
  const [showEditorAssistant, setShowEditorAssistant] = React.useState(false);
  const [editorAssistantPosition, setEditorAssistantPosition] = React.useState({
    x: 0,
    y: 0,
  });

  // 1. 修改类型定义
  type PanelState = "open" | "closed";

  // 2. 修改函数定义
  const openLibraryPanel = (
    panelState: PanelState,
    setPanelState: React.Dispatch<React.SetStateAction<PanelState>>
  ) => {
    setStandardLibraryPanelState("closed");
    setMaterialLibraryPanelState("closed");
    setEnterpriseLibraryPanelState("closed");
    setPanelState(panelState === "closed" ? "open" : "closed");
  };

  React.useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setIsPreviewMode(false);
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, []);

  const handleSelect = (item: TreeItemData) => {
    setSelectedItem(item);
    setCurrentLine(0);
  };

  const handleAddChild = (parent: TreeItemData) => {
    const newId = `${parent.id}.${parent.children.length + 1}`;
    const newItem = {
      id: newId,
      title: `New ${parent.type === "chapter" ? "Section" : "Item"}`,
      type: parent.type === "chapter" ? "section" : "item",
      content: "",
      children: [],
    };
    const updatedStructure = JSON.parse(JSON.stringify(articleStructure));
    const findAndAddChild = (items: TreeItemData[]) => {
      for (const item of items) {
        if (item.id === parent.id) {
          item.children.push(newItem);
          return true;
        }
        if (item.children && findAndAddChild(item.children)) {
          return true;
        }
      }
      return false;
    };
    findAndAddChild(updatedStructure);
    setArticleStructure(updatedStructure);
  };

  interface TreeItemData {
    id: string;
    title: string;
    type: string;
    content: string;
    children: TreeItemData[];  // 明确定义为递归类型
  }

  const handleDelete = (itemToDelete: TreeItemData) => {
    const updatedStructure = JSON.parse(JSON.stringify(articleStructure));
    const findAndDeleteItem = (items: TreeItemData[]) =>
      items.filter((item) => {
        if (item.id === itemToDelete.id) {
          return false;
        }
        if (item.children) {
          item.children = findAndDeleteItem(item.children);
        }
        return true;
      });
    const newStructure = findAndDeleteItem(updatedStructure);
    setArticleStructure(newStructure);
    if (selectedItem && selectedItem.id === itemToDelete.id) {
      setSelectedItem(null);
    }
  };

  const handleContentChange = (content: string) => {
    if (selectedItem) {
      const updatedStructure = JSON.parse(JSON.stringify(articleStructure));
      const findAndUpdateContent = (items: TreeItemData[]) => {
        for (const item of items) {
          if (item.id === selectedItem.id) {
            item.content = content;
            return true;
          }
          if (item.children && findAndUpdateContent(item.children)) {
            return true;
          }
        }
        return false;
      };
      findAndUpdateContent(updatedStructure);
      setArticleStructure(updatedStructure);
      setSelectedItem({ ...selectedItem, content });
    }
  };

  const handleUpdate = (id: string, newTitle: string) => {
    const updatedStructure = JSON.parse(JSON.stringify(articleStructure));
    const findAndUpdateTitle = (items: TreeItemData[]) => {
      for (const item of items) {
        if (item.id === id) {
          item.title = newTitle;
          return true;
        }
        if (item.children && findAndUpdateTitle(item.children)) {
          return true;
        }
      }
      return false;
    };
    findAndUpdateTitle(updatedStructure);
    setArticleStructure(updatedStructure);
    if (selectedItem && selectedItem.id === id) {
      setSelectedItem({ ...selectedItem, title: newTitle });
    }
  };

  const handleVersionChange = (version: string) => {
    if (version === "edit") {
      setIsVersionDialogOpen(true);
    } else {
      setCurrentVersion(version);
      console.log(`Switching to version ${version}`);
    }
  };

  const handleAddVersion = () => {
    if (newVersionName && !versions.includes(newVersionName)) {
      setVersions([...versions, newVersionName]);
      setCurrentVersion(newVersionName);
      setNewVersionName("");
      setIsVersionDialogOpen(false);
    }
  };

  const handleEditVersion = (version: string) => {
    setEditingVersion(version);
    setNewVersionName(version);
  };

  const handleUpdateVersion = () => {
    if (newVersionName && !versions.includes(newVersionName)) {
      const updatedVersions = versions.map((v) =>
        v === editingVersion ? newVersionName : v
      );
      setVersions(updatedVersions);
      if (currentVersion === editingVersion) {
        setCurrentVersion(newVersionName);
      }
      setEditingVersion(null);
      setNewVersionName("");
    }
  };

  const handleDeleteVersion = (versionToDelete: string) => {
    const updatedVersions = versions.filter((v) => v !== versionToDelete);
    setVersions(updatedVersions);
    if (currentVersion === versionToDelete) {
      setCurrentVersion(updatedVersions[0] || "");
    }
  };

  const handleAddChapter = () => {
    const newChapter = {
      id: `${articleStructure.length + 1}`,
      title: `Chapter ${articleStructure.length + 1}`,
      type: "chapter",
      content: "",
      children: [],
    };
    setArticleStructure([...articleStructure, newChapter]);
  };

  const filteredStructure = React.useMemo(() => {
    if (!searchTerm) return articleStructure;
    const filterItems = (items: TreeItemData[]): TreeItemData[] => {
      return items
        .filter((item) => {
          const matchesSearch = item.title
            .toLowerCase()
            .includes(searchTerm.toLowerCase());
          const childMatches =
            item.children && filterItems(item.children).length > 0;
          return matchesSearch || childMatches;
        })
        .map((item) => ({
          ...item,
          children: item.children ? filterItems(item.children) : [],
        }));
    };
    return filterItems(articleStructure);
  }, [articleStructure, searchTerm]);

  const handlePreview = () => {
    setIsPreviewMode(!isPreviewMode);
    setStandardLibraryPanelState("closed");
    setMaterialLibraryPanelState("closed");
    setEnterpriseLibraryPanelState("closed");
  };

  const renderPreview = () => {
    const fullContent = articleStructure
      .map((chapter) => {
        return `${chapter.content}\n\n${chapter.children
          .map((section) => section.content)
          .join("\n\n")}`;
      })
      .join("\n\n");

    return (
      <div className="p-8 max-w-4xl mx-auto">
        <ReactMarkdown 
          components={{
            ...mdxComponents,
            blockquote: ({ children, ...props }) => (
              <blockquote {...props}>{children}</blockquote>
            )
          }} 
          remarkPlugins={mdxOptions.remarkPlugins} 
          rehypePlugins={mdxOptions.rehypePlugins}
        >
          {fullContent}
        </ReactMarkdown>
      </div>
    );
  };

  const handleLineClick = (lineIndex: number) => {
    setCurrentLine(lineIndex);
  };

  const handleEditorAssistantTrigger = (e: React.SyntheticEvent) => {
    const rect = e.currentTarget.getBoundingClientRect();
    setEditorAssistantPosition({
      x: rect.left,
      y: rect.bottom + window.scrollY,
    });
    setShowEditorAssistant(true);
  };

  const handleEditorAssistantClose = () => {
    setShowEditorAssistant(false);
  };

  const handleEditorAssistantGenerate = (generatedContent: string) => {
    if (selectedItem) {
      handleContentChange(selectedItem.content + generatedContent);
    }
    setShowEditorAssistant(false);
  };

  const handleItemSelect = (itemId:string) => {
    const findAndSelectItem = (items: TreeItemData[]) => {
      for (const item of items) {
        if (item.id === itemId) {
          setSelectedItem(item);
          return true;
        }
        if (item.children && findAndSelectItem(item.children)) {
          return true;
        }
      }
      return false;
    };
    findAndSelectItem(articleStructure);
  };

  const handleStructureWheel = (e: React.WheelEvent) => {
    e.preventDefault();
    const direction = e.deltaY > 0 ? 1 : -1;
    const flatItems = articleStructure.flat(Infinity);
    const currentIndex = flatItems.findIndex(
      (item) => item.id === selectedItem?.id
    );
    const newIndex = Math.max(
      0,
      Math.min(flatItems.length - 1, currentIndex + direction)
    );
    setSelectedItem(flatItems[newIndex]);
  };

  const handleSelectTemplate = (templateId: string) => {
    console.log(`Selected template: ${templateId}`);
    setIsTemplateModalOpen(false);
    // Here you would typically load the selected template
  };

  return (
    <div className="flex h-screen overflow-hidden">
      {/* Vertical Menu Bar */}
      <div className="w-16 bg-gray-800 flex flex-col items-center justify-between py-4">
        <div className="space-y-4 w-full">
          <Button
            variant="ghost"
            size="icon"
            className="w-full flex justify-center"
          >
            <Home className="h-6 w-6 text-white" />
          </Button>
        </div>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              className="w-full flex justify-center"
            >
              <User className="h-6 w-6 text-white" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuLabel>我的账户</DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuItem>
              <User className="mr-2 h-4 w-4" />
              <span>个人资料</span>
            </DropdownMenuItem>
            <DropdownMenuItem>
              <Settings className="mr-2 h-4 w-4" />
              <span>设置</span>
            </DropdownMenuItem>
            <DropdownMenuItem>
              <LogOut className="mr-2 h-4 w-4" />
              <span>退出登陆</span>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      {/* Main Content Area */}
      <div className="flex flex-1 flex-col overflow-hidden">
        {/* Top Functionality Bar */}
        <TopFunctionBar
          onAddChapter={handleAddChapter}
          currentVersion={currentVersion}
          versions={versions}
          onVersionChange={handleVersionChange}
          onPreviewToggle={handlePreview}
          isPreviewMode={isPreviewMode}
          openLibraryPanel={openLibraryPanel}
          enterpriseLibraryPanelState={enterpriseLibraryPanelState}
          materialLibraryPanelState={materialLibraryPanelState}
          standardLibraryPanelState={standardLibraryPanelState}
          setEnterpriseLibraryPanelState={setEnterpriseLibraryPanelState}
          setMaterialLibraryPanelState={setMaterialLibraryPanelState}
          setStandardLibraryPanelState={setStandardLibraryPanelState}
        />

        {/* Content Area with Sidebar and Editor */}
        <div className="flex flex-1 overflow-hidden">
          {!isPreviewMode && (
            <>
              {/* Main Panel */}
              <div className="w-[calc(256px*1.2)] flex-shrink-0 border-r bg-background overflow-hidden">
                <Tabs
                  defaultValue="structure"
                  className="w-full h-full flex flex-col"
                >
                  <TabsList className="grid w-full grid-cols-2">
                    <TabsTrigger value="structure">结构</TabsTrigger>
                    <TabsTrigger value="dialogue">对话</TabsTrigger>
                  </TabsList>
                  <TabsContent
                    value="structure"
                    className="flex-1 flex flex-col overflow-hidden"
                  >
                    <div className="px-4 py-2">
                      <Input
                        placeholder="Search document..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="h-8 mb-2"
                      />
                    </div>
                    <div
                      className="px-2 flex-1 overflow-auto"
                      onWheel={handleStructureWheel}
                    >
                      {filteredStructure.map((chapter) => (
                        <TreeItem
                          key={chapter.id}
                          item={chapter}
                          onSelect={handleSelect}
                          onAddChild={handleAddChild}
                          onDelete={handleDelete}
                          onUpdate={handleUpdate}
                          selectedId={selectedItem?.id ?? null}
                          isEditMode={isEditMode}
                        />
                      ))}
                    </div>
                    <div className="px-4 py-2 border-t">
                      <div className="flex gap-2 mb-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={handleAddChapter}
                          className="flex-1"
                        >
                          <Plus className="mr-2 h-4 w-4" />
                          增加章
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setIsTemplateModalOpen(true)}
                          className="flex-1"
                        >
                          选择模板
                        </Button>
                      </div>
                      <Button
                        variant={isEditMode ? "default" : "secondary"}
                        size="sm"
                        onClick={() => setIsEditMode(!isEditMode)}
                        className="w-full"
                      >
                        <Edit className="mr-2 h-4 w-4" />
                        {isEditMode ? "完成" : "编辑"}
                      </Button>
                    </div>
                  </TabsContent>
                  <TabsContent
                    value="dialogue"
                    className="flex-1 overflow-hidden"
                  >
                    <ChatPanel />
                  </TabsContent>
                </Tabs>
              </div>

              {/* Full Text Scroll Bar */}
              <FullTextScrollBar
                structure={articleStructure}
                selectedItemId={selectedItem?.id ?? null}
                onItemSelect={handleItemSelect}
              />

              {/* Editor Area */}
              <div className="flex-1 overflow-auto">
                <div className="container mx-auto py-4 px-6 max-w-4xl">
                  {selectedItem ? (
                    <>
                      <h2 className="text-sm font-normal mb-4">
                        {selectedItem.title}
                      </h2>
                      <MarkdownEditor
                        content={selectedItem.content}
                        onChange={handleContentChange}
                        currentLine={currentLine}
                        onLineClick={handleLineClick}
                        onAITrigger={handleEditorAssistantTrigger}
                      />
                    </>
                  ) : (
                    <div className="flex items-center justify-center h-full text-muted-foreground p-4 text-sm">
                      请从左侧文档结构中选择一个项目进行编辑。
                    </div>
                  )}
                </div>
              </div>
            </>
          )}

          {isPreviewMode && renderPreview()}
        </div>
      </div>

      {/* Right-side panels */}
      <EnterpriseLibrary
        state={enterpriseLibraryPanelState}
        onStateChange={(state) => setEnterpriseLibraryPanelState(state as "open" | "closed")}
      />
      <MaterialLibrary
        state={materialLibraryPanelState}
        onStateChange={(state) => setMaterialLibraryPanelState(state as "open" | "closed")}
      />
      <StandardLibrary
        state={standardLibraryPanelState}
        onStateChange={(state) => setStandardLibraryPanelState(state as "open" | "closed")}
      />

      {/* Version Dialog */}
      <Dialog open={isVersionDialogOpen} onOpenChange={setIsVersionDialogOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>编辑版本</DialogTitle>
            <DialogDescription>
              在这里您可以添加、编辑或删除版本。
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>版本</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {versions.map((version) => (
                  <TableRow key={version}>
                    <TableCell className="font-medium">{version}</TableCell>
                    <TableCell className="text-right">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEditVersion(version)}
                      >
                        编辑
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDeleteVersion(version)}
                      >
                        删除
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
          <div className="flex items-center space-x-2">
            <Input
              value={newVersionName}
              onChange={(e) => setNewVersionName(e.target.value)}
              placeholder={editingVersion ? "编辑版本名称" : "新版本名称"}
            />
            <Button
              onClick={editingVersion ? handleUpdateVersion : handleAddVersion}
            >
              {editingVersion ? "更新" : "加"}
            </Button>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setIsVersionDialogOpen(false);
                setEditingVersion(null);
                setNewVersionName("");
              }}
            >
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Template Selection Modal */}
      <TemplateSelectionModal
        isOpen={isTemplateModalOpen}
        onClose={() => setIsTemplateModalOpen(false)}
        onSelectTemplate={handleSelectTemplate}
      />

      {/* Editor Assistant */}
      <EditorAssistant
        isVisible={showEditorAssistant}
        onClose={handleEditorAssistantClose}
        onGenerate={handleEditorAssistantGenerate}
        position={editorAssistantPosition}
      />
    </div>
  );
}
